import { Client } from '@stomp/stompjs'
import { ElMessage as Message, ElLoading as Loading } from 'element-plus'
const state = () => ({
  client: null,
})

const mutations = {
  saveClient(state, client) {
    state.client = client
  },
  clearClient(state) {
    if (state.client) {
      state.client.deactivate()
      state.client = null
    }
  },
}

const actions = {
  connect({ commit, state, rootState, dispatch }) {
    if (state.client) {
      return
    }

    const client = new Client({
      brokerURL: '/stomp?Authorization=' + rootState.loginUser.token,
      reconnectDelay: 10000, // 重连间隔5秒
      // heartbeatIncoming: 4000, // 可配置心跳检测[9](@ref)
      // heartbeatOutgoing: 4000,
    })

    let loadingInstance = null

    client.onConnect = () => {
      console.log('Stomp Connected')

      if (loadingInstance) {
        loadingInstance.close()
        loadingInstance = null
      }

      client.subscribe('/user/messages/sessionKicked', ({}) => {
        Message({
          message: '会话被踢',
          type: 'error',
        })
        dispatch('loginUser/gotoLogin', null, { root: true })
      })
    }

    const maxReconnectAttempts = 5
    let reconnectAttempts = 0

    client.onWebSocketError = () => {
      if (loadingInstance == null) {
        loadingInstance = Loading.service({
          text: '正在尝试重连服务器...',
          background: 'rgba(0, 0, 0, 0.3)',
        })
        console.log('Stomp Connecting...', loadingInstance)
      }

      if (++reconnectAttempts == maxReconnectAttempts) {
        loadingInstance.close()
        Message({
          message: '服务器连接失败',
          type: 'error',
        })
        dispatch('loginUser/gotoLogin', null, { root: true })
      }
    }

    client.onDisconnect = () => {
      console.log('Stomp Disconnected')
    }

    client.activate() // 激活连接，库会自动管理重连
    commit('saveClient', client)
  },
  disConnect({ commit }) {
    commit('clearClient')
  },
}

export default {
  namespaced: true,
  state: state,
  actions: actions,
  mutations: mutations,
}
